package com.huaxindata.im.main.addFriend;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxindata.common.http.ResponseBean;
import com.huaxindata.common.util.ToastUtil;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ContactConstants;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.HistoryContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.service.MessageService;
import com.huaxindata.im.service.OnMessageSendListener;
import com.huaxindata.im.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 添加好友页面，一个是被请求添加为好友，一个是用户填写信息
 * 请求添加别人为好友，并显示部分要添加好友的信息
 */
public class AddFriendActivity extends AppCompatActivity {

    public static final String TAG = "AddFriendActivity";
    private Toolbar         mToolbar;
    private AvatarImageView mIconIv;
    private TextView        mNameExpandTv;
    private TextView        mNickNameTv;
    private EditText        mRequestInfoEt;//请求信息
    private View            mRequestTv, mAcceptTv, mRefuseTv;
    /**
     * 如果是从MessageFragment中接收到的请求或者是
     * 发现模块中搜索出来的好友
     * 则只传以下几个参数
     */
    private String mNickName;
    private String mIcon;
    private String mClientId;
    private String mRequestInfo;
    /**
     * 用于标记是添加好友还是删除好友，通过Intent传递过来
     * function值为1的话，为添加好友，值为2则为被请求添加好友
     */
    private int function = 0;
    /**
     * 如果是从搜索界面搜出来的联系人，则传对象过来
     */
    private Contact mPerson;

    private MessageService mService;
    private boolean        mIsBind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
        bindToService();
        initData();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        function = intent.getIntExtra(ImConstants.FUNCTION_ADD_FRIEND, 0);
        if (function == 0) {
            ToastUtil.showToast(this, "未知错误");
            finish();
        } else if (function == ImConstants.FUNCTION_REQUEST) {
            mPerson = intent.getParcelableExtra(ImConstants.CONTACT);
            if (mPerson == null) {
                mNickName = intent.getStringExtra(ContactConstants.NICK_NAME);//从发现页面中搜索出来的用户传过来
                mClientId = intent.getStringExtra(ContactConstants.CLIENT_ID);
                mIcon = intent.getStringExtra(ContactConstants.ICON);
                mRequestInfo = intent.getStringExtra(ImConstants.REQUEST_INFO);
            }
        } else if (function == ImConstants.FUNCTION_RESPONSE) {
            mPerson = intent.getParcelableExtra(ImConstants.CONTACT);
        }
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.activity_add_friend_toolbar);
        mIconIv = (AvatarImageView) findViewById(R.id.activity_add_friend_icon);
        mNickNameTv = (TextView) findViewById(R.id.activity_add_friend_name);
        mNameExpandTv = (TextView) findViewById(R.id.activity_add_friend_icon_expand);
        mRequestInfoEt = (EditText) findViewById(R.id.activity_add_friend_info);
        mRequestTv = findViewById(R.id.activity_add_friend_request);
        mAcceptTv = findViewById(R.id.activity_add_friend_accept);
        mRefuseTv = findViewById(R.id.activity_add_friend_refuse);
        setSupportActionBar(mToolbar);
        if (function == ImConstants.FUNCTION_REQUEST) {//申请
            mToolbar.setTitle("申请好友");
            mRequestTv.setVisibility(View.VISIBLE);
            mAcceptTv.setVisibility(View.GONE);
            mRefuseTv.setVisibility(View.GONE);
            mNickNameTv.setText(mPerson.getNickName());
            mPerson.showImageIcon(this, mIconIv, mNameExpandTv);
            mRequestInfoEt.setEnabled(true);
            mRequestInfoEt.setHint("请输入添加理由，比如我是" + UserManager.getNickName() + "。");
        } else if (function == ImConstants.FUNCTION_RESPONSE) {//处理
            mToolbar.setTitle("好友添加请求");
            mRequestTv.setVisibility(View.GONE);
            mAcceptTv.setVisibility(View.VISIBLE);
            mRefuseTv.setVisibility(View.VISIBLE);
            mNickNameTv.setText(mNickName);
            Glide.with(this).load(mIcon).into(mIconIv);
            mRequestInfoEt.setText("添加理由：" + mRequestInfo);
            mRequestInfoEt.setEnabled(false);
        }
    }

    public void onClick(View v) {
        if (v.getId() == R.id.activity_add_friend_request) {
            if (mPerson == null) {
                sendRequestFriendMessage(mClientId, mRequestInfoEt.getText().toString());
            } else {
                sendRequestFriendMessage(mPerson.getClientId(), mRequestInfoEt.getText().toString());
            }
            onBackPressed();
        } else if (v.getId() == R.id.activity_add_friend_accept) {
            addFriend();
        } else if (v.getId() == R.id.activity_add_friend_refuse) {
            close();
        }
    }

    /**
     * 接收添加好友
     */
    private void addFriend() {
        Call<ResponseBean> call;
        if (mPerson == null) {
            call = RetrofitClient.getHttpApi().addFriend
                    (UserManager.getClientId(), mClientId);
        } else {
            call = RetrofitClient.getHttpApi().addFriend
                    (UserManager.getClientId(), mPerson.getClientId());
        }
        //更新至web,发送消息
        call.enqueue(new Callback<ResponseBean>() {
            @Override
            public void onResponse(Call<ResponseBean> call, Response<ResponseBean> response) {
                if (!response.isSuccessful()) {
                    ToastUtil.showToast(AddFriendActivity.this, response.message());
                    Log.e(TAG, "xxx==添加好友失败");
                    finish();
                    return;
                }
                ResponseBean responseBean = response.body();
                if (responseBean.getState() == 1) {//成功
                    ContactManager.initData();//重新下载好友列表
                    sendResponseFriendMessage(mPerson == null ? mClientId : mPerson.getClientId(), null, true);
                    //  HistoryContactManager.hideChatHistory(mPerson == null ? mClientId : mPerson.getClientId());
                } else {
                    ToastUtil.showToast(AddFriendActivity.this, responseBean.getMsg());
                    finish();
                }
            }

            @Override
            public void onFailure(Call<ResponseBean> call, Throwable t) {
                ToastUtil.showToast(AddFriendActivity.this, "网络或服务器异常,请重试");
            }
        });
    }

    /**
     * 拒绝添加好友，删除最近联系人
     */
    private void close() {
        if (mPerson == null) {
            sendResponseFriendMessage(mClientId, null, false);
            HistoryContactManager.deleteHistory(mClientId);
        } else {
            sendResponseFriendMessage(mPerson.getClientId(), null, false);
            HistoryContactManager.deleteHistory(mPerson.getClientId());
        }
        finish();
    }

    /**
     * 发送添加好友请求
     *
     * @param rqstId
     * @param extraInfo
     */
    private void sendRequestFriendMessage(String rqstId, String extraInfo) {
        ChatMessage message = new ChatMessage(ChatMessageBody.Type.SYSTEM, UserManager.getClientId(), rqstId, System.currentTimeMillis());
        ChatSysMessageBody chatSysMessageBody = new ChatSysMessageBody(ChatMessageBody.Type.SYSTEM);
        chatSysMessageBody.action = ChatSysMessageBody.SysMessageType.ACTION_RQST_FED;
        if (TextUtils.isEmpty(extraInfo)) {
            extraInfo = "我是" + UserManager.getNickName();
        }

        chatSysMessageBody.content = chatSysMessageBody.action + ChatMessage.PREX + UserManager.getNickName() + ChatMessage.PREX + extraInfo;
        message.messageBody = chatSysMessageBody;
        sendMessage(message);
    }

    /**
     * 回复好友添加请求，同意还是拒绝
     */
    private void sendResponseFriendMessage(String respId, String extraInfo, boolean accept) {
        final String acp = accept ? "1" : "0";
        ChatMessage message = new ChatMessage(ChatMessageBody.Type.SYSTEM, UserManager.getClientId(), respId, System.currentTimeMillis());
        ChatSysMessageBody chatSysMessageBody = new ChatSysMessageBody(ChatMessageBody.Type.SYSTEM);
        chatSysMessageBody.action = ChatSysMessageBody.SysMessageType.ACTION_RESP_FED;
        if (extraInfo == null) {
            chatSysMessageBody.content = ChatSysMessageBody.SysMessageType.ACTION_RESP_FED + ChatMessage.PREX
                    + UserManager.getNickName() + ChatMessage.PREX + acp;

        } else {
            chatSysMessageBody.content = ChatSysMessageBody.SysMessageType.ACTION_RESP_FED + ChatMessage.PREX
                    + UserManager.getNickName() + ChatMessage.PREX + acp + ChatMessage.PREX + extraInfo;
        }
        message.messageBody = chatSysMessageBody;
        sendMessage(message);
    }

    /**
     * 发送添加 接收添加 拒绝添加 等message
     *
     * @param message
     */
    private void sendMessage(ChatMessage message) {
        String topic = "chat/" + message.receiver;
        mService.sendMessage(topic, message, new OnMessageSendListener() {
            @Override
            public void sendSuccess(ChatMessage message) {

                Toast.makeText(AddFriendActivity.this, "消息已送出", Toast.LENGTH_SHORT).show();
                // 接收添加 将message 插入数据库，并好友提示
                Log.e("lwjing", "addFriend："+message.toString());
                ChatSysMessageBody chatSysMessageBody = (ChatSysMessageBody) message.getMessageBody();
                String action = chatSysMessageBody.getAction();
                String[] systemMessageInfo = chatSysMessageBody.getSystemMessageInfo(chatSysMessageBody.content);
                if (systemMessageInfo == null || systemMessageInfo.length == 0) {
                    return;
                }
                if (ChatSysMessageBody.SysMessageType.ACTION_RESP_FED.equals(action) && "1".equals(systemMessageInfo[2])) {
                    //将消息置为已读
                    message.read=1;
                    //接收添加好友
                    MessageStore.insert(message);
                    //更新最近联系人表 relation 好友
                    //ContactStore.updateRelation(message.sender,1);
                    Contact tmp = ContactManager.getContactById(mPerson.getClientId());
                    if (tmp==null){
                        ContactStore.insert(mPerson,1,message.timestamp);
                    }else{
                        ContactStore.insert(tmp,1,message.timestamp);
                    }

                    finish();
                }

            }

            @Override
            public void sendFailure(ChatMessage message) {
                Toast.makeText(AddFriendActivity.this, "消息发送失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 绑定到后台接收消息的service
     */
    private void bindToService() {
        Intent intent = new Intent(this, MessageService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        mIsBind = true;
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((MessageService.MyBinder) service).getService();
            mIsBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mIsBind = false;
        }
    };

    /**
     * 与后台接收消息的service解决绑定
     */
    private void unBindService() {
        if (mIsBind) {
            unbindService(mServiceConnection);
            mIsBind = false;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unBindService();
    }
}
